<template>
  <div>
    <a-form
      class="w-[60%] mx-auto"
      :label-col="{
        span: 9,
      }"
      layout="vertical"
      :model="form"
      v-if="form"
      ref="formRef"
    >
      <a-form-item :label="t('Data source')">
        <a-select
          :placeholder="t('Please select data source')"
          :options="translateOptions(connectionType, t)"
          v-model:value="type"
          allow-clear
          @change="setOption"
          @focus="reset"
        ></a-select>
      </a-form-item>

      <a-form-item
        :label="t('Cashier platform')"
        required
        name="cashierPlatform"
        v-if="[dataSourceItems.SQL, dataSourceItems.API].includes(type)"
      >
        <a-tree-select
          :tree-data="cashierPlatformList"
          v-model:value="form.cashierPlatform"
          allow-clear
        ></a-tree-select>
      </a-form-item>

      <a-form-item
        :label="t('Electronic scale brand')"
        v-else-if="type === dataSourceItems.ElectronicScale"
        required
        name="electronicScaleBrand"
      >
        <a-select v-model:value="form.electronicScaleBrand" :options="electronicOptions"></a-select>
      </a-form-item>

      <a-form-item
        :label="t('File path')"
        v-else-if="type === dataSourceItems.FILE"
        required
        name="filePath"
      >
        <a-input v-model:value="form.filePath"></a-input>
      </a-form-item>
      <a-row>
        <a-col>
          <a-button @click="nextStep" type="primary" :disabled="!type">
            {{ t('Next step') }}
          </a-button>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { apiChengConfig, apiConfig, apiFileConfig, fetchOptions } from '@/api/modules';
import { fieldsDropdownList } from '@/data/data';
import { translateOptions } from '@/utils/common/format';
import type { FormInstance } from 'ant-design-vue';
import type { LabelValueType } from 'ant-design-vue/es/vc-tree-select/interface';
import { fetchStoreDataMap } from '../fetch';
import { connectionType } from '../options';
import type { ConnectionType, DataConnectionForm } from '../types';
import { API_STORE, dataSourceItems } from './data';

const { t } = useI18n();
const formRef = ref<FormInstance>();
const cashierPlatformList = ref<LabelValueType[]>([]);
const electronicOptions = ref<LabelValueType[]>([]);
const type = ref<ConnectionType>('');
const form = defineModel<DataConnectionForm>('form');
const step = defineModel<number>('step');

const nextStep = async () => {
  try {
    await formRef.value?.validate();

    if (form.value) {
      form.value.type = type.value;
      /* 当为API时，单独请求接口 */
      if (type.value === dataSourceItems.API) {
        let result = await fetchStoreDataMap[form.value.cashierPlatform as API_STORE]?.();
        form.value.api = result;
      } else {
        await fetchDataSource();
      }
      /* 其他情况均拉取数据库信息 */
      if (type.value === dataSourceItems.ElectronicScale) {
        const { data } = await apiChengConfig(form.value.electronicScaleBrand);
        fieldsDropdownList.value = data.data;
        step.value = 3;
      }

      if (type.value === dataSourceItems.FILE) {
        step.value = 3;
        await apiFileConfig(type.value);
      } else {
        step.value = 2;
      }
    }
  } catch (error) {}
};
const reset = () => {
  if (form.value) {
    form.value.cashierPlatform = '';
  }

  formRef.value?.resetFields();
};
const setOption = async (value: any) => {
  let map: Record<string, string> = {
    [dataSourceItems.SQL]: 'database',
    [dataSourceItems.API]: 'api',
    [dataSourceItems.ElectronicScale]: 'scale',
  };
  if ([dataSourceItems.SQL, dataSourceItems.API].includes(value)) {
    const { data } = await fetchOptions(map[value]);
    cashierPlatformList.value = data.data.map(v => {
      if (v.children && v.children.length > 0) {
        v.selectable = false;
      }
      return v;
    });
  } else if (value === dataSourceItems.ElectronicScale) {
    const { data } = await fetchOptions('scale');
    electronicOptions.value = data.data;
  }
};
const fetchDataSource = async () => {
  if (!form.value) return;
  if ([dataSourceItems.SQL, dataSourceItems.API].includes(type.value)) {
    const { data } = await apiConfig(form.value.cashierPlatform);
    form.value.sql = data.data.data;
  }
};
</script>

<style lang="scss" scoped></style>
